import Vue from 'vue'
import VueRouter from 'vue-router'
import Reg from '@/views/Reg/Reg.vue'
import Login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import Home from '@/views/Menus/Home/Home.vue'
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
import ArtList from '@/views/Menus/Article/ArtList.vue'
import store from '@/store'

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      // 2. home 作为 子路由规则,一般子路由不以/开头,会拼接父路由的路径
      // 如果要以/开头则不拼接父路由
      { path: 'home', component: Home },
      // 用户信息的子路由规则
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: UserAvatar },

      // 重置密码的子路由规则
      { path: 'user-Pwd', component: UserPwd },
      // 文章分类组件的子路由规则
      { path: 'art-cate', component: ArtCate },
      // 文章列表组件的子路由规则

      { path: 'art-list', component: ArtList }
    ]
  }

]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  // 白名单,数组里面写可以访问的页面
  const whiteList = ['/login', '/reg']
  // includes判断元素是否在数组中,返回一个布尔值
  // 如果不在白名单中就去登录页,在就放行
  if (!token && !whiteList.includes(to.path)) {
    next('/login')
    Vue.prototype.$message.error('您还没登录哦亲')
  } else {
    next()
  }
})

export default router
